//
//  TimeInterval+AG.swift
//  AGF
//
//  Created by zhuxuhong on 2021/1/6.
//

import UIKit

extension Calendar.Component: Comparable {
    public static func < (lhs: Self, rhs: Self) -> Bool {
        return "\(lhs)" < "\(rhs)"
    }
}

extension TimeInterval {
    public func bw_secondsToDateComponentsJoinedString(units: DateComponentValueSet) -> String {
        let components = bw_secondsToDateComponents()
        var str = ""
        
        let sorted = units.sorted{ $0.keys.first! < $1.keys.first! }
        for unit in sorted {
            let unitKey = unit.keys.first!
            let unitValue = unit.values.first!
            if let comp = components.first(where: { $0.keys.first == unitKey }),
            let value = comp.values.first {
                str += value + " " + unitValue + " "
            }
        }
        
        return str
    }
    
    public func bw_secondsToDateComponents(
        numberFormatWidth: Int = 2,
        paddingCharacter: String = "0"
    ) -> DateComponentValueSet {
        
        let time = Int(self)
        let days = time / (24*3600)
        let hours = (time - days*24*3600) / 3600
        let minutes = (time - days*24*3600 - hours*3600) / 60
        let seconds = time - days*24*3600 - hours*3600 - minutes*60
        
        let nf = NumberFormatter()
        nf.formatWidth = numberFormatWidth
        nf.paddingCharacter = paddingCharacter
        nf.paddingPosition = .beforePrefix
        
        var comps: DateComponentValueSet = []
        if let v = nf.string(from: .init(value: days)) {
            comps.insert([.day: v])
        }
        if let v = nf.string(from: .init(value: hours)) {
            comps.insert([.hour: v])
        }
        if let v = nf.string(from: .init(value: minutes)) {
            comps.insert([.minute: v])
        }
        if let v = nf.string(from: .init(value: seconds)) {
            comps.insert([.second: v])
        }
        return comps
    }
}
